from app.models import StudyRecord, Student, Content
from app.extensions import db

class StudyRecordService:
    """学习记录管理服务"""

    @staticmethod
    def update_study_record_byKnow(student_id,content_id,content_type,duration,mastery_score):
        """添加学习记录"""
        new_record = StudyRecord(
            study_time=db.func.now(),
            student_id=student_id,
            content_id=content_id,
            study_type=content_type,
            duration=duration,
            mastery_score=mastery_score
        )
        db.session.add(new_record)
        return new_record
    @staticmethod
    def create_record(student_id: int, content_id: int, 
                     study_type: str, duration: int, score: int) -> dict:
        """创建学习记录"""
        if not Student.query.get(student_id):
            return {'code': 404, 'msg': '学生不存在'}
        if not Content.query.get(content_id):
            return {'code': 404, 'msg': '学习内容不存在'}
        
        new_record = StudyRecord(
            study_type=study_type,
            duration=duration,
            mastery_score=score,
            student_id=student_id,
            content_id=content_id
        )
        db.session.add(new_record)
        db.session.commit()
        return {'code': 201, 'msg': '记录创建成功', 'record_id': new_record.record_id}

    @staticmethod
    def get_learning_report(student_id: int) -> dict:
        """生成学习报告"""
        records = StudyRecord.query.filter_by(student_id=student_id).all()
        total_duration = sum(r.duration for r in records)
        avg_score = sum(r.mastery_score for r in records) / len(records) if records else 0
        return {
            'code': 200,
            'data': {
                'total_study_time': total_duration,
                'average_score': round(avg_score, 1),
                'completed_tasks': len(records)
            }
        }